<?php
/**
 * 报名管理页面
 * 功能：管理考试报名信息
 * 权限：仅考试项目管理员可访问
 */

session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
require_once 'database.php';

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 权限验证函数
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id, $conn) {
        $roles = [];
        try {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("s", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $roles[] = $row['role'];
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            error_log("获取用户角色失败: " . $e->getMessage());
        }

        return $roles;
    }
}

// 权限验证
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 获取考试ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    $_SESSION['error_message'] = "无效的考试项目ID";
    header('Location: exam_projects.php');
    exit();
}

$exam = null;
$error_message = '';
$success_message = '';

// 获取考试信息
try {
    $sql = "SELECT * FROM exams WHERE id = ? AND status = 'active'";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception("数据库查询准备失败");
    }

    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $_SESSION['error_message'] = "考试项目不存在或已被删除";
        header('Location: exam_projects.php');
        exit();
    }

    $exam = $result->fetch_assoc();
    $stmt->close();

} catch (Exception $e) {
    $_SESSION['error_message'] = "获取考试信息失败: " . $e->getMessage();
    header('Location: exam_projects.php');
    exit();
}

$page_title = '报名管理 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .info-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .feature-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
            margin-bottom: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .feature-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.15);
        }

        .feature-icon {
            font-size: 3rem;
            margin-bottom: 20px;
            color: #28a745;
        }

        .btn-back {
            margin-bottom: 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-item {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
<!-- 统一导航栏 -->
<?php
if (file_exists('common/navigation.php')) {
    include_once 'common/navigation.php';
} else {
    echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="user_home.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
}
?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 返回按钮 -->
    <div class="btn-back">
        <a href="exam_projects.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> 返回项目列表
        </a>
    </div>

    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-user-check"></i> 报名管理
        </h1>
        <p class="mb-0">项目：<?php echo htmlspecialchars($exam['exam_name']); ?></p>
    </div>

    <!-- 考试信息 -->
    <div class="info-card">
        <h5><i class="fas fa-info-circle"></i> 考试信息</h5>
        <div class="row">
            <div class="col-md-3">
                <strong>考试日期：</strong><br>
                <?php echo date('Y-m-d', strtotime($exam['exam_date'])); ?>
            </div>
            <div class="col-md-3">
                <strong>科目数量：</strong><br>
                <?php echo $exam['subject_count']; ?> 门
            </div>
            <div class="col-md-3">
                <strong>每科学生数：</strong><br>
                <?php echo $exam['students_per_subject']; ?> 人
            </div>
            <div class="col-md-3">
                <strong>当前进度：</strong><br>
                <span class="badge bg-success">阶段 <?php echo $exam['progress']; ?></span>
            </div>
        </div>
    </div>

    <!-- 功能模块 -->
    <div class="row">
        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-user-plus"></i>
                </div>
                <h5>学生报名</h5>
                <p class="text-muted">管理学生报名信息</p>
                <button class="btn btn-success" onclick="manageStudentSignup()">
                    <i class="fas fa-cog"></i> 管理报名
                </button>
            </div>
        </div>

        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-file-import"></i>
                </div>
                <h5>批量导入</h5>
                <p class="text-muted">批量导入学生信息</p>
                <button class="btn btn-info" onclick="batchImport()">
                    <i class="fas fa-upload"></i> 批量导入
                </button>
            </div>
        </div>

        <div class="col-md-4">
            <div class="feature-card">
                <div class="feature-icon">
                    <i class="fas fa-file-export"></i>
                </div>
                <h5>导出报名表</h5>
                <p class="text-muted">导出学生报名统计</p>
                <button class="btn btn-warning" onclick="exportSignup()">
                    <i class="fas fa-download"></i> 导出数据
                </button>
            </div>
        </div>
    </div>

    <!-- 报名统计 -->
    <div class="info-card">
        <h5><i class="fas fa-chart-bar"></i> 报名统计</h5>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-number text-primary">0</div>
                <div class="text-muted">已报名学生</div>
            </div>
            <div class="stat-item">
                <div class="stat-number text-success">
                    <?php echo $exam['students_per_subject'] * $exam['subject_count']; ?>
                </div>
                <div class="text-muted">计划招生数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number text-warning">0</div>
                <div class="text-muted">待审核</div>
            </div>
            <div class="stat-item">
                <div class="stat-number text-info">0%</div>
                <div class="text-muted">报名完成率</div>
            </div>
        </div>
    </div>

    <!-- 最近报名 -->
    <div class="info-card">
        <h5><i class="fas fa-clock"></i> 最近报名</h5>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>报考科目</th>
                    <th>报名时间</th>
                    <th>状态</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td colspan="5" class="text-center text-muted">暂无报名记录</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    function manageStudentSignup() {
        Swal.fire({
            title: '学生报名管理',
            text: '学生报名管理功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }

    function batchImport() {
        Swal.fire({
            title: '批量导入',
            text: '批量导入功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }

    function exportSignup() {
        Swal.fire({
            title: '导出报名表',
            text: '导出功能正在开发中...',
            icon: 'info',
            confirmButtonText: '确定'
        });
    }
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>